#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <LockInfo/Plugin.h>

#import "FWStatusbarViewCell.h"
#import "FWCommon.h"
#import "FWBadgeView.h"
#import "FWApplication.h"
#import "FWColorIconView.h"


@implementation FWStatusbarViewCell

@synthesize label, labelIcon1, labelIcon2, labelIcon3, badge, labelIndent, swipeAction, swipeTarget;

static CGFloat const kMinToolbarHeight = 20;
static CGFloat const kToolbarIconHeight = 16;
static CGFloat const kToolbarSeparatorWidth = 2;


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (id)initWithFrame:(CGRect)frame theme:(LITheme*)theme toolbarItems:(NSArray*)navItems
{
    if ((self = [super initWithFrame:frame theme:theme toolbarItems:navItems])) {
        labelIndent = 0;
        
        UIImageView* icn1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kToolbarIconHeight, kToolbarIconHeight)];
        icn1.backgroundColor = [UIColor clearColor];
        icn1.image = [UIImage imageWithContentsOfFile:[[NSBundle bundleForClass:[self class]] pathForResource:@"context" ofType:@"png"]];
        icn1.userInteractionEnabled = NO;
        icn1.hidden = YES;

        FWColorIconView* icn2 = [[FWColorIconView alloc] initWithFrame:CGRectMake(0, 0, kToolbarIconHeight, kToolbarIconHeight)];
        icn2.userInteractionEnabled = NO;
        icn2.hidden = YES;

        FWColorIconView* icn3 = [[FWColorIconView alloc] initWithFrame:CGRectMake(0, 0, kToolbarIconHeight, kToolbarIconHeight)];
        icn3.userInteractionEnabled = NO;
        icn3.hidden = YES;

        LILabel* lbl = FWLILabel(CGRectZero);
        lbl.frame = CGRectZero;
//        lbl.style = table.theme.summaryStyle;
        lbl.backgroundColor = [UIColor clearColor];
        lbl.userInteractionEnabled = NO;
        
        FWBadgeView* bdg = [[FWBadgeView alloc] initWithFrame:CGRectMake(0, 0, kToolbarIconHeight, frame.size.height)];
        bdg.userInteractionEnabled = NO;
        
        self.label = lbl;
        self.labelIcon1 = icn1;
        self.labelIcon2 = icn2;
        self.labelIcon3 = icn3;
        self.badge = bdg;
        
        [self addSubview:icn1];
        [self addSubview:icn2];
        [self addSubview:icn3];
        [self addSubview:lbl];
        [self addSubview:bdg];
        
        [icn1 release];
        [icn2 release];
        [icn3 release];
        [bdg release];
        
        [self setNeedsLayout];
        
        UITapGestureRecognizer* touch = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(statusbarTapped:)];
        [self addGestureRecognizer:touch];
        [touch release];

        UISwipeGestureRecognizer* swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(statusbarSwiped:)];
        swipe.direction = (UISwipeGestureRecognizerDirection)(UISwipeGestureRecognizerDirectionLeft |
                                                              UISwipeGestureRecognizerDirectionRight);
        [self addGestureRecognizer:swipe];
        [swipe release];
    }
    
    return self;
}

- (void)dealloc
{
    [label release];
    [labelIcon1 release];
    [labelIcon2 release];
    [labelIcon3 release];
    [badge release];
    [swipeTarget release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Item layout and dimensioning

+ (CGFloat)heightForStatusbarWithTheme:(LITheme*)theme
{
    CGFloat height = theme.detailStyle.font.leading;
    if (height < kMinToolbarHeight)
        height = kMinToolbarHeight;
    
    return height;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGRect rect = self.frame;
    CGFloat fontHeight = label.style.font.leading;
    //self.label.backgroundColor = [UIColor yellowColor];
    
    // Ensure that the badge is at the end of the frame
    CGSize badgeSize;
    self.badge.smallestHeight = kToolbarIconHeight;
    if (!badge.hidden)
        badgeSize = [badge sizeThatFits:CGSizeMake(0, self.toolbarHeight)];
    else 
        badgeSize = CGSizeZero;

    CGRect labelFrame = CGRectMake(labelIndent, 
                                   (self.toolbarHeight - fontHeight) / 2,
                                   rect.size.width - labelIndent - kToolbarSeparatorWidth,
                                   fontHeight);

    if (!badge.hidden) {
        badge.frame = CGRectMake(rect.size.width - badgeSize.width - kToolbarSeparatorWidth,
                                 (self.toolbarHeight - badgeSize.height) / 2,
                                 badgeSize.width,
                                 badgeSize.height);
        labelFrame.size.width -= badgeSize.width + kToolbarSeparatorWidth;
    }

    if (!labelIcon1.hidden) {
        labelIcon1.frame = CGRectMake(labelFrame.origin.x,
                                      (self.toolbarHeight - kToolbarIconHeight) / 2,
                                      kToolbarIconHeight,
                                      kToolbarIconHeight);
        
        labelFrame.origin.x += kToolbarSeparatorWidth + labelIcon1.frame.size.width;
        labelFrame.size.width -= kToolbarSeparatorWidth + labelIcon1.frame.size.width;
    }

    if (!labelIcon2.hidden || !labelIcon3.hidden) {
        if (!labelIcon2.hidden)
            labelFrame.size.width -= kToolbarSeparatorWidth + kToolbarIconHeight;
        if (!labelIcon3.hidden)
            labelFrame.size.width -= kToolbarSeparatorWidth + kToolbarIconHeight;

        CGSize labelSize = [self.label.text sizeWithFont:self.label.style.font];
        if (labelSize.width < labelFrame.size.width)
            labelFrame.size = labelSize;

        NSInteger iconPos = labelFrame.origin.x + labelFrame.size.width + kToolbarSeparatorWidth;
        if (!labelIcon2.hidden) {
            labelIcon2.frame = CGRectMake(iconPos,
                                          (self.toolbarHeight - kToolbarIconHeight) / 2,
                                          kToolbarIconHeight,
                                          kToolbarIconHeight);
            
            labelIcon2.color = self.label.style.textColor;
            [labelIcon2 setNeedsDisplay];
            
            iconPos += kToolbarIconHeight + kToolbarSeparatorWidth;
        }

        if (!labelIcon3.hidden) {
            labelIcon3.frame = CGRectMake(iconPos,
                                          (self.toolbarHeight - kToolbarIconHeight) / 2,
                                          kToolbarIconHeight,
                                          kToolbarIconHeight);
            
            labelIcon3.color = self.label.style.textColor;
            [labelIcon3 setNeedsDisplay];
        }
    }

    // LILabel seems to stretch its text on rotation unless we do this
    label.frame = labelFrame;
    [self.label setNeedsDisplay];
    
    [self setNeedsDisplay];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Attribute and information access

- (void)setInformationWithTheme:(LITheme*)theme indent:(CGFloat)indent label:(NSString*)text
{
    // Label should use detail style font with summary style color
    self.label.style = theme.summaryStyle;
    self.label.text = text;
    self.labelIcon1.hidden = !([text length] > 0);
    
    self.toolbarHeight = [FWStatusbarViewCell heightForStatusbarWithTheme:theme];
    self.labelIndent = indent;
    
    [self setNeedsLayout];
}

- (void)setBadgeValue:(NSString*)value hidden:(BOOL)hidden
{
    if (([value length] == 0) || [value isEqualToString:@"0"])
        hidden = YES;
    
    if (![badge.text isEqualToString:value] || (badge.hidden != hidden)) {
        DebugLog(@"LI:PICommon: Badge value changed = %@", value);
        
        badge.text = value;
        badge.hidden = hidden;
        
        if (!hidden)
            [badge setNeedsDisplay];
        
        [self setNeedsLayout];
        [self setNeedsDisplay];
    }
}


// ******************************************************************************************
#pragma mark -
#pragma mark Input handling

- (void)statusbarTapped:(id)sender
{
    if (self.toolbar.items.count > 0) {
        UIBarButtonItem* btn = [self.toolbar.items objectAtIndex:0];
        [btn.target performSelector:btn.action withObject:btn]; 
    }
}

- (void)statusbarSwiped:(id)sender
{
    if (swipeTarget)
        [swipeTarget performSelector:swipeAction withObject:[NSNumber numberWithInt:((UISwipeGestureRecognizer*)sender).direction]];
}

@end
